package com.axx.android.subject;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;

import com.axx.android.R;
import com.axx.android.base.BaseActivity;
import com.axx.android.common.BaseModel;
import com.axx.android.common.Constants;
import com.axx.android.common.SJRefreshView;
import com.axx.android.profile.message.model.MessageLetter;
import com.axx.android.utils.GsonUtils;
import com.axx.android.utils.HttpUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.loadmore.SimpleLoadMoreView;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class SubjectHistoryActivity extends BaseActivity {

    @Bind(R.id.btn_back)
    Button mBtnBack;
    @Bind(R.id.vs_error)
    ViewStub mVsError;
    @Bind(R.id.rv_list)
    RecyclerView mRvList;
    @Bind(R.id.refresh_view)
    SJRefreshView mRefreshView;
    private int curPage = 1;
    private int pageSize = 20;
    private View viewError;

    private List<SubjectHistory.BeforeSubjectListBean> list = new ArrayList<>();
    private SubjectHistoryAdapter subjectHistoryAdapter;


    @Override
    public int getLayoutId() {
        return R.layout.activity_subject_history;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        initAdapter();
        refresh();
        mRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                curPage = 1;
                fetchHistory();
            }
        });
    }

    private void initAdapter() {
        subjectHistoryAdapter = new SubjectHistoryAdapter(R.layout.view_item_subject_history, list);
        mRvList.setAdapter(subjectHistoryAdapter);
        mRvList.setLayoutManager(new LinearLayoutManager(this));
        subjectHistoryAdapter.setLoadMoreView(new SimpleLoadMoreView());
        subjectHistoryAdapter.setEmptyView(R.layout.view_default_emtpy, mRvList);
        subjectHistoryAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                curPage++;
                fetchHistory();
            }
        }, mRvList);
        subjectHistoryAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(SubjectHistoryActivity.this, SubjectNowActivity.class);
                String id = subjectHistoryAdapter.getData().get(position).getId();
                intent.putExtra("subjectId", id);
                startActivity(intent);
            }
        });
    }

    private void fetchHistory() {
        HashMap<String, String> map = new HashMap<>();
        map.put("nowpage", curPage + "");
        map.put("pagenum", pageSize + "");
        HttpUtils.post(Constants.Url.Subject.SUBJECT_HISTORY, map, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                mRefreshView.setRefreshing(false);
                try {
                    BaseModel<SubjectHistory> model = GsonUtils.fromJson(result, new TypeToken<BaseModel<SubjectHistory>>() {
                    });
                    if (model.isSuccess()) {
                        showSuccess(model.data.getBeforeSubjectList());
                    } else {
                        mRefreshView.setRefreshing(false);
                        showErrorView();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError() {
                mRefreshView.setRefreshing(false);
                showErrorView();
            }
        });
    }

    private void showSuccess(List<SubjectHistory.BeforeSubjectListBean> letterList) {
        mRefreshView.setRefreshing(false);
        if (viewError != null) {
            viewError.setVisibility(View.GONE);
        }
        if (curPage == 1) {
            subjectHistoryAdapter.setNewData(letterList);
            subjectHistoryAdapter.disableLoadMoreIfNotFullPage(mRvList);
        } else {
            int loadCount = letterList.size();
            subjectHistoryAdapter.addData(letterList);
            if (loadCount < pageSize) {
                subjectHistoryAdapter.loadMoreEnd();
            } else {
                subjectHistoryAdapter.loadMoreComplete();
            }
        }
    }


    private void showErrorView() {
        if (viewError == null) {
            viewError = mVsError.inflate();
            viewError.findViewById(R.id.btn_retry).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    viewError.setVisibility(View.GONE);
                    refresh();
                }
            });
        } else {
            viewError.setVisibility(View.VISIBLE);
        }

    }


    private void refresh() {
        mRefreshView.post(new Runnable() {
            @Override
            public void run() {
                mRefreshView.setRefreshing(true);
                fetchHistory();
            }
        });
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
